package com.pni.games.poker.hands;

import com.pni.game.cards.Card;

public class TwoPair extends PokerHand {

	private int topPair;
	private int bottomPair;
	private int kicker;

	public TwoPair(Card[] cards) {
		super(cards, HandType.TWO_PAIR);
	}

	public int getTopPair() {
		return topPair;
	}

	public int getBottomPair() {
		return bottomPair;
	}

	public int getKicker() {
		return kicker;
	}

	@Override
	protected void determineHandValue() {
		int[] values = new int[POKER_HAND_SIZE];
		for (int i = 0; i < cards.length; i++) {
			values[i] = cards[i].getRank().value();
		}
		this.bottomPair = -1;
		this.topPair = -1;
		this.kicker = -1;
		for (int i = 0; i < values.length; i++) {
			int pair = -1;
			if (bottomPair != values[i] && topPair != values[i]) {
				for (int j = i + 1; j < values.length; j++) {
					if (values[i] == values[j]) {
						if (pair == -1) {
							pair = values[i];
						} else {
							// found 3 of a kind, not possible for this hand
							throw new IllegalArgumentException(cards.toString() + " not valid combination of cards for two pair.");
						}
					}
				}
				if (pair == -1) {
					// found kicker if iterate through whole list and found no pair
					if (kicker == -1) {
						kicker = values[i];
					} else {
						// kicker already found, this isnt valid.
						throw new IllegalArgumentException(cards.toString() + " not valid combination of cards for two pair.");
					}
				} else {
					if (bottomPair == -1) {
						bottomPair = pair;
					} else {
						int previousPair = bottomPair;
						bottomPair = Math.min(previousPair, pair);
						topPair = Math.max(previousPair, pair);
					}
				}
			}
		}
	}

	@Override
	protected int compareSameHand(PokerHand otherHand) {
		TwoPair otherTwoPair = (TwoPair) otherHand;
		int otherTopPair = otherTwoPair.getTopPair();
		if (this.topPair > otherTopPair) {
			return 1;
		} else if (this.topPair == otherTopPair) {
			int otherBottomPair = otherTwoPair.getBottomPair();
			if (this.bottomPair > otherBottomPair) {
				return 1;
			} else if (this.bottomPair == otherBottomPair) {
				int otherKicker = otherTwoPair.getKicker();
				if (this.kicker > otherKicker) {
					return 1;
				} else if (this.kicker == otherKicker) {
					return 0;
				} else {
					return -1;
				}
			} else {
				return -1;
			}
		} else {
			return -1;
		}
	}
}
